package hmvictor.jpql.types;

import java.awt.Color;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.UIManager;

/**
 *
 * @author Victor
 */
public class TextFieldBasedEditor implements Editor{
    private final JTextField textField=new JTextField();
    private final ValueConverter converter;

    public TextFieldBasedEditor(ValueConverter converter) {
        this.converter = converter;
    }
    
    @Override
    public JComponent getComponent() {
        return textField;
    }

    @Override
    public Object getValue() {
        try{
            Object value = converter.convert(textField.getText());
            textField.setBackground(UIManager.getColor("TextField.background"));
            return value;
        }catch(InvalidEditorValueException ex){
//            textField.setBackground(Color.PINK);
            throw ex;
        }catch(Exception ex) {
//            textField.setBackground(Color.PINK);
            throw new InvalidEditorValueException(ex);
        }
    }

    @Override
    public JComponent getComponent(Object initValue) {
        textField.setText(initValue == null? "": String.valueOf(initValue));
        return textField;
    }
    
}
